package com.tianda.his.modules.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianda.his.modules.system.dto.RoleDto;
import com.tianda.his.modules.system.entity.SysRole;
import com.tianda.his.modules.system.entity.SysRoleUser;
import com.tianda.his.modules.system.mapper.SysRoleMapper;
import com.tianda.his.modules.system.mapper.SysRoleUserMapper;
import com.tianda.his.modules.system.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianda.his.modules.system.service.SysRoleUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author jinken
 * @since 2025-09-12
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    protected SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    protected SysRoleUserService sysRoleUserService;

    @Override
    public List<Long> getRoleIdsByUserId(Long userId) {

        LambdaQueryWrapper<SysRoleUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleUser::getUserId, userId);

        List<SysRoleUser> sysRoleUsers = sysRoleUserMapper.selectList(queryWrapper);

        List<Long> roleIds = sysRoleUsers.stream().map(SysRoleUser::getRoleId).toList();

        return roleIds;
    }

    @Override
    public void saveRoleUser(Long userId, List<Long> roleIds) {
        //删除历史角色
        LambdaUpdateWrapper<SysRoleUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysRoleUser::getUserId, userId);
        sysRoleUserMapper.delete(updateWrapper);

        if(!CollUtil.contains(roleIds,-1L)){
            //将角色id转换成角色用户对象
            List<SysRoleUser> roleUsers = roleIds.stream().map(roleId -> {
                SysRoleUser roleUser = new SysRoleUser();
                roleUser.setUserId(userId);
                roleUser.setRoleId(roleId);
                return roleUser;
            }).toList();

            sysRoleUserService.saveBatch(roleUsers);
        }


    }

    @Override
    public Page<SysRole> listRoleForPage(RoleDto roleDto) {

        LambdaUpdateWrapper<SysRole> updateWrapper = new LambdaUpdateWrapper<>();
        //TODO 组织搜索条件
        Page<SysRole> sysRolePage = new Page<>(roleDto.getPageNum(), roleDto.getPageSize());

        this.page(sysRolePage, updateWrapper);

        return sysRolePage;
    }
}
